import { Http, HttpError, HttpRequestOptions } from './http'
import Axios, { AxiosRequestConfig, AxiosError } from 'axios'


export class AxiosHttp<Result = any> extends Http<Result> {
    private axios

    constructor(config?: AxiosRequestConfig) {
        super()
        this.axios = Axios.create(config)
    }

    async request(url: string, options: HttpRequestOptions): Promise<Result> {
        try {
            const res = await this.axios({
                url: url,
                method: options.method,
                params: options.query,
                data: options.body,
                headers: options.header,
                signal: options.signal,
                responseType: options.responseType
            })
            return res.data
        } catch (error: any) {
            if (Axios.isCancel(error)) {
                const httpError = new HttpError(error.message, { url, options })
                httpError.isAbort = true
                return Promise.reject(httpError)
            }else if (Axios.isAxiosError(error)) {
                const httpError = new HttpError(error.message, { url, options })
                if (error.response) {
                    httpError.response = {
                        status: error.response.status,
                        body: error.response.data
                    }
                }
                return Promise.reject(httpError)
            } else {
                return Promise.reject(error)
            }
        }
    }
}
